# -*- coding: utf-8 -*-
import webapp2
import exceptions

from Person import Person
from webapp2 import uri_for

transfer_dict = {u'No': False, u'Yes': True, '':False}

class DisplayData(webapp2.RequestHandler):

    def get(self, *args, **kwargs):
        persons_query = sorted(list(Person.query()))
        ability_groups = {'dancers' :[], 'singers':[], 'other_skills':[]}

        total_persons = 0
        for person in persons_query:
            surname = person.surname
            name = person.name
            can_dance = person.can_dance
            can_sing = person.can_sing
            other_skills = person.other_skills
            person_id = surname + ' ' + name

            if other_skills:
                ability_groups['other_skills'].append((person_id, other_skills))
            if can_dance:
                ability_groups['dancers'].append((person_id, other_skills))
            if can_sing:
                ability_groups['singers'].append((person_id, other_skills))

            total_persons += 1

        universals = set(ability_groups['dancers']) & set(ability_groups['singers']) & set(ability_groups['other_skills'])
        dancers_and_singers = set(ability_groups['dancers']) & set(ability_groups['singers']) - universals
        dancers_and_others = set(ability_groups['dancers']) & set(ability_groups['other_skills']) - universals
        singers_and_others = set(ability_groups['singers']) & set(ability_groups['other_skills']) - universals
        singers_only = set(ability_groups['singers']) - set(ability_groups['other_skills']) - set(ability_groups['dancers'])
        dancers_only = set(ability_groups['dancers']) - set(ability_groups['other_skills']) - set(ability_groups['singers'])
        others_only = set(ability_groups['other_skills']) - set(ability_groups['singers']) - set(ability_groups['dancers'])

        self.response.write("""
        <html>
            <head>
                <title>Регистрация на кастинг спектакля</title>
            </head>

        """)

        if total_persons == 0:
            self.response.write('<body>Пока никто не зарегистрировался, ты будешь первым. <ul>')
        else:
            self.response.write('<body>Список уже зарегистрировавшихся людишек <ul>')

        if universals:
            self.response.write(u""" <li> Танцуют, поют и еще что-то умеют </li><ul>""")
            for person in sorted(list(universals)):
                self.response.write(u'<li> %s (%s) </li>' %(person[0], person[1]))
            self.response.write('</ul>')
        if dancers_and_singers:
            self.response.write(u"""<li> Танцуют и поют </li><ul> """)
            for person in sorted(list(dancers_and_singers)):
                self.response.write(u'<li> %s </li>' % (person[0]))
            self.response.write('</ul>')
        if dancers_and_others:
            self.response.write(u""" <li> Танцуют и могут что-то еще</li> <ul> """)
            for person in sorted(list(dancers_and_others)):
                self.response.write(u'<li> %s (%s)</li>' % (person[0], person[1]))
            self.response.write('</ul>')
        if singers_and_others:
            self.response.write(u"""  <li> Поют и могут что-то еще</li> <ul> """)
            for person in sorted(list(singers_and_others)):
                self.response.write(u'<li> %s </li>' % (person[0]))
            self.response.write('</ul>')
        if singers_only:
            self.response.write(u"""  <li> Только поют</li> <ul> """)
            for person in sorted(list(singers_only)):
                self.response.write(u'<li> %s </li>' % (person[0]))
            self.response.write('</ul>')
        if dancers_only:
            self.response.write(u"""  <li> Только танцуют</li> <ul> """)
            for person in sorted(list(dancers_only)):
                self.response.write(u'<li> %s </li>' % (person[0]))
            self.response.write('</ul>')
        if others_only:
            self.response.write(u"""  <li> Умееют только что-то, кроме танцев и пения</li> <ul> """)
            for person in sorted(list(others_only)):
                self.response.write(u'<li> %s (%s) </li>' % (person[0], person[1]))
            self.response.write('</ul>')

        self.response.write(u"""</ul>
        <form action="%s" method="post">
            <label for="person" font=><b>Расскажи нам про себя</b></label> <br>
            <label for="surname">Фамилия<br></label>
                <input id="surname" type="text" name="person_surname"> <br>
            <label for="name">Имя<br></label>
                <input id="name" type="text" name="person_name"><br><br>

                <input type="radio" name="can_dance" value="Yes">Я умею танцевать
                <input type="radio" name="can_dance" value="No">Я не умею танцевать<br>
                <input type="radio" name="can_sing" value="Yes">Я умею петь
                <input type="radio" name="can_sing" value="No">Я не умею петь<br><br>

            <label for="skills">А что еще ты умеешь?</label>
                <input id="other_skills" type="text" name="skills" size="40"><br>
                <input type="submit" name="Добавить">
        </form>
       """ % uri_for('add'))

        # self.response.write("""
        # <form action="%s" method="post"><input type="submit" value="Удалить всех зарегистрировавшихся"></form>"""
        # % uri_for('clear'))

        self.response.write("""
        Обновите страницу, чтобы увидеть внесенные вами изменения.
        </body>
        </html>
        """)


class ClearPersons(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearPersons, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        for key in Person.query().iter(keys_only=True):
            key.delete()
        self.redirect(uri_for('show'))


class AddPerson(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddPerson, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        try:
            name = unicode(self.request.get('person_name'))
            surname = unicode(self.request.get('person_surname'))
            can_dance = unicode(self.request.get('can_dance'))
            can_sing = unicode(self.request.get('can_sing'))
            other_skills = unicode(self.request.get('skills'))


        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return

        new_person = Person(surname=surname,
                            name=name,
                            can_dance=transfer_dict[can_dance],
                            can_sing=transfer_dict[can_sing],
                            other_skills=other_skills)
        if new_person.can_dance or new_person.can_sing or new_person.other_skills:
            new_person.put()

        self.redirect(uri_for('show'))
